package com.test33_反射;

/**
 * 反射与单例设计模式
 */
public class Demo04_Singleton {

    public static void main(String[] args) {
//        test1();
        test2();
    }

    /**
     * 多线程情况下，会实例化多个单例对象
     */
    public static void test1() {
        for (int x = 0; x < 10; x++) {
            new Thread(() -> {
                Singleton singleton = Singleton.getInstance();
                System.out.println(singleton);
            }, "单例操作线程 - "+x).start();
        }
    }

    public static void test2() {
        for (int x = 0; x < 10; x++) {
            new Thread(() -> {
                Singleton2 singleton = Singleton2.getInstance();
                System.out.println(singleton);
            }, "单例操作线程 - "+x).start();
        }
    }
}

/**
 * 传统单例设计模式
 */
class Singleton {
    private static Singleton instance;

    private Singleton() {
        System.out.println("【" + Thread.currentThread().getName() + "】实例化Singleton类的对象。");
    }

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    @Override
    public String toString() {
        return "【VIP】李兴华编程训练营：yootk.ke.qq.com";
    }
}

/**
 * 懒汉式单例设计模式的正确使用姿势
 */
class Singleton2 {
    private static volatile Singleton2 instance;

    private Singleton2() {
        System.out.println("【" + Thread.currentThread().getName() + "】实例化Singleton类的对象。");
    }

    public static Singleton2 getInstance() {
        if (instance == null) {
            synchronized (Singleton2.class) {   // 同步代码块
                if (instance == null) {
                    instance = new Singleton2();
                }
            }
        }
        return instance;
    }

    @Override
    public String toString() {
        return "【VIP】李兴华编程训练营：yootk.ke.qq.com";
    }
}
